#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Download available firmware update for Bosch Smart Home (*.fw)
# ==============================================================================
readonly REPO="BoschSmartHome/bosch-smart-home-files"
readonly API_BASE="https://api.github.com/repos/${REPO}/contents/firmware-otau-files"

# Ensure OTAU folder exists
mkdir -p "/data/otau"

bashio::log.info "Running the Bosch OTA updater..."

# Fetch GitHub firmware data
if ! curl -fsL "${API_BASE}" >/dev/null; then
    bashio::log.warning "⚠️ Can't fetch data from GitHub — retry in 5 hours."
    exec sleep 18000
fi

fetch_fw_files() {
    local api_url
    api_url="$1"

    local data
    data=$(curl -s "$api_url")

    # Some GitHub responses return a single object instead of an array
    [[ $(echo "$data" | jq -r 'type') == "object" ]] && data="[$data]"

    echo "$data" | jq -r '.[] | @base64' | while read -r entry; do
        _jq() { echo "$entry" | base64 --decode | jq -r "$1"; }

        local type
        type=$(_jq '.type')
        local name
        name=$(_jq '.name')
        local path
        path=$(_jq '.path')
        local download_url
        download_url=$(_jq '.download_url')

        if [[ "$type" == "dir" ]]; then
            # Recursive call for subfolders
            local encoded_path
            encoded_path=$(python3 -c "import urllib.parse; print(urllib.parse.quote('''${path}''', safe=''))")
            fetch_fw_files "https://api.github.com/repos/${REPO}/contents/${encoded_path}?ref=main"
        elif [[ "$name" == *.fw && -n "$download_url" ]]; then
            local target
            target="/data/otau/${name}"

            # Skip already downloaded files
            [[ -f "${target}" ]] && continue

            # Download firmware
            curl -s -L -o "${target}" "${download_url}"
        fi
    done
}
fetch_fw_files "${API_BASE}"

exec sleep 259200 # Sleep for 3 days before next check
